/*
  Author: Ionel Crisu - crisuionel@yahoo.com
  support@FlashExtended.com
*/
package com.flashextended.utils.server.phphttpservice
{
	import com.adobe.serialization.json.JSON;
	
	import mx.controls.Alert;
	import mx.managers.CursorManager;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
		
	public class PhpHttpService
	{
		
		
		private var service:HTTPService;
		private var mainDestination:String;
		
		private var okCallBack:Function;
		private var faultCallBack:Function;
		
		public static var faultERROR:String = "An error has ocured while connecting to server";
		public static var jsonERROR:String = "JSON decode error.";
		public static var keepAliveError:String = "Error, server might be down.";
		private static var errorTitle1:String = "Error!";
				
		public function PhpHttpService()
		{
		}
		
		private function connect(serverURL:String=""):void
		{
			mainDestination = serverURL;
			try{
				service = new HTTPService();
				service.url = mainDestination;
				service.useProxy = false;
				service.method = "POST";
				service.resultFormat = "text";
				}catch(e:Error)
				{
					Alert.show(keepAliveError, errorTitle1);
				}			
		}
		/**
		 * Init connection with the server
		 * @serverURL - server service URL
		 * @additionalVars - additional vars to send to server
		 */ 
		public function makeConnection(serverURL:String="", additionalVars:Object = null, callBack:Function=null, faultCallBack:Function=null):void
		{
			CursorManager.setBusyCursor();
			connect(serverURL);
			this.okCallBack = callBack;
			this.faultCallBack = faultCallBack;
			var vars:Object;
			(additionalVars!=null)?vars = additionalVars: vars = null;
			(vars!=null)?service.request = vars: null;
			service.addEventListener(ResultEvent.RESULT, jsonResult);
			service.addEventListener(FaultEvent.FAULT, faultEvent);
			service.send();	
		}
			
		private function jsonResult(e:ResultEvent):void
		{
			CursorManager.removeBusyCursor();
			var rawData:String = String(e.result);
			try{
				var data:Object = com.adobe.serialization.json.JSON.decode(rawData);
				if(data.status == "OK")
				{
					okCallBack(data);
				}
				else
				{
					Alert.show(data.error, errorTitle1);
					if(faultCallBack!=null)
					{
						faultCallBack();
					}					
				}
			}catch(e:Error)
			{
				Alert.show(jsonERROR, errorTitle1);
				if(faultCallBack!=null)
				{
					faultCallBack();
				}
			}
		}
		
		private function faultEvent(e:FaultEvent):void
		{
			Alert.show(faultERROR, errorTitle1);
		}
				

	}
}